package com.stkcall.library;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.util.Log;

import androidx.core.app.ActivityCompat;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * <p>------------------------------------------------------
 * <p>Copyright (C) company, All rights reserved.
 * <p>------------------------------------------------------
 *
 * @author: xujie
 * @date: 7/9/22
 */
public class DeviceUtils {
    private static final String TAG = "DeviceUtils";

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }

    /**
     * 获取当前系统上的语言列表(Locale列表)
     *
     * @return 语言列表
     */
    public static Locale[] getSystemLanguageList() {
        return Locale.getAvailableLocales();
    }

    /**
     * 获取手机厂商
     *  HuaWei
     * @return 手机厂商
     */
    public static String getPhoneBrand() {
        return Build.BRAND;
    }

    /**
     * 获取手机型号
     * @return 手机型号
     */
    public static String getPhoneModel() {
        return Build.MODEL;
    }

    /**
     * 获取当前手机系统版本号
     * Android     10
     * @return 系统版本号
     */
    public static String getVersionRelease() {
        return Build.VERSION.RELEASE;
    }

    /**
     * 获取当前手机设备名
     * 设备统一型号,不是"关于手机"的中设备名
     * @return 设备名
     */
    public static String getDeviceName() {
        return Build.DEVICE;
    }

    /**
     * HUAWEI HWELE ELE-AL00 10
     * @return
     */
    public static String getPhoneDetail() {
        return DeviceUtils.getPhoneBrand() + " " + DeviceUtils.getDeviceName() + " " + DeviceUtils.getPhoneModel() + " " + DeviceUtils.getVersionRelease();
    }

    /**
     * 获取手机主板名
     *
     * @return 主板名
     */
    public static String getDeviceBoard() {
        return Build.BOARD;
    }


    /**
     * 获取手机厂商名
     * HuaWei
     * @return 手机厂商名
     */
    public static String getDeviceManufacturer() {
        return Build.MANUFACTURER;
    }

    /**
     * 跳转录音设置
     * @param context
     * @param className
     */
    public static void gotoRecordAudioSetting(Context context, String className) {
        try {
            String packageName = "com.android.phone";
            String split = className;
            String[] aar = split.split("/");
            if(aar.length > 1) {
                packageName = aar[0];
                className = aar[1];
            }

            ComponentName componentName = new ComponentName(packageName, className);
            Intent intent = new Intent();
            intent.setComponent(componentName);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } catch (Exception e) {
            Log.d(TAG, "gotoRecordAudioSetting: Exception");
            e.printStackTrace();
        }
    }

    /**
     * 检查OPPO手机自动录音功能是否开启，true已开启  false未开启
     *
     * @return
     */
    public static int checkOppoRecord(Context context) {
        try {
            int key = Settings.Global.getInt(context.getContentResolver(), "oppo_all_call_audio_record");
            Log.d(TAG, "Oppo key:" + key);
            //0代表OPPO自动录音未开启,1代表OPPO自动录音已开启
            return key;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 检查小米手机自动录音功能是否开启，true已开启  false未开启
     *
     * @return
     */
    public static int checkXiaomiRecord(Context context) {
        try {
            int key = Settings.System.getInt(context.getContentResolver(), "button_auto_record_call");
            Log.d(TAG, "Xiaomi key:" + key);
            //0是未开启,1是开启
            return key;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 检查华为手机自动录音功能是否开启，true已开启  false未开启
     *
     * @return
     */
    public static int checkHuaweiRecord(Context context) {
        try {
            int key = Settings.Secure.getInt(context.getContentResolver(),
                    "enable_record_auto_key");
            Log.d(TAG, "Huawei key: " + key);
            //0代表华为自动录音未开启,1代表华为自动录音已开启
            return key;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 检查录音key
     * @param context
     * @param keyName
     * @return
     */
    public static int checkRecord(Context context, String keyName) {
        try {
            int key = Settings.Secure.getInt(context.getContentResolver(),
                    keyName);
            Log.d(TAG, "other Secure key: " + key);
            return key;
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
            try {
                int key = Settings.System.getInt(context.getContentResolver(), keyName);
                Log.d(TAG, "other System key: " + key);
                return key;
            } catch (Settings.SettingNotFoundException e2) {
                e2.printStackTrace();
                try {
                    int key = Settings.Global.getInt(context.getContentResolver(), keyName);
                    Log.d(TAG, "other Global key: " + key);
                    return key;
                } catch (Settings.SettingNotFoundException settingNotFoundException) {
                    settingNotFoundException.printStackTrace();
                }
            }
        }
        return -1;
    }


    /**
     * 获取Sim卡信息
     * @param context
     * @return
     */
    public static List<PhoneInfo> getSimInfo(Context context) {

        List<PhoneInfo> list = new ArrayList<>();

        if (list.isEmpty()) {
            list = getSimInfo1(context);
        }

        if (list.isEmpty()) {
            list = getSimInfo2(context);
        }

        if(list.isEmpty()) {
            list = getSimInfo3(context);
        }
        return list;
    }

    public static List<PhoneInfo> getSimInfo1(Context context){
        List<PhoneInfo> list = new ArrayList<>();

        try {
            ContentResolver contentResolver = context.getContentResolver();
            Cursor cursor = contentResolver.query(Uri.parse("content://telephony/siminfo"),
                    new String[]{"_id", "sim_id", "icc_id", "display_name"}, "0=0",
                    new String[]{}, null);
            if (null != cursor) {
                while (cursor.moveToNext()) {
                    String icc_id = cursor.getString(cursor.getColumnIndex("icc_id"));
                    String display_name = cursor.getString(cursor.getColumnIndex("display_name"));
                    int sim_id = cursor.getInt(cursor.getColumnIndex("sim_id"));
                    int _id = cursor.getInt(cursor.getColumnIndex("_id"));

                    Log.d("Q_M", "icc_id-->" + icc_id);
                    Log.d("Q_M", "sim_id-->" + sim_id);
                    Log.d("Q_M", "display_name-->" + display_name);
                    Log.d("Q_M", "subId或者说是_id->" + _id);
                    Log.d("Q_M", "---------------------------------");
                    if (sim_id != -1) {
                        PhoneInfo info = new PhoneInfo();
                        info.simSerialNumber = icc_id;
                        info.simOperatorName = display_name;
                        info.simId = sim_id;
                        list.add(info);
                    }
                }
                cursor.close();
            }
        }catch (Exception e){
            Log.d(TAG, "getSimInfo1 Exception");
            e.printStackTrace();
        }
        return list;
    }

    public static List<PhoneInfo> getSimInfo2(Context context){
        List<PhoneInfo> list = new ArrayList<>();

        try {
            SubscriptionManager mSubscriptionManager = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                mSubscriptionManager = SubscriptionManager.from(context);
                if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                    List<SubscriptionInfo> mSubInfoList = mSubscriptionManager.getActiveSubscriptionInfoList();
                    for (int i = 0; i < mSubInfoList.size(); i++) {
                        SubscriptionInfo subscriptionInfo = mSubInfoList.get(i);
                        PhoneInfo info = new PhoneInfo();
                        info.simId = i;
                        info.simSerialNumber = subscriptionInfo.getIccId();
                        info.simOperatorName = subscriptionInfo.getDisplayName().toString();
                        list.add(info);
                    }
                }
            }
        }catch (Exception e){
            Log.d(TAG, "getSimInfo2 Exception");
            e.printStackTrace();
        }
        return list;
    }

    public static List<PhoneInfo> getSimInfo3(Context context){
        List<PhoneInfo> list = new ArrayList<>();

        try {
            TelecomManager telecomManager = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                telecomManager = (TelecomManager) context.getSystemService(Context.TELECOM_SERVICE);
                if (telecomManager != null) {
                    @SuppressLint("MissingPermission")
                    List<PhoneAccountHandle> phoneAccountHandleList = telecomManager.getCallCapablePhoneAccounts();
                    for (int i = 0; i < phoneAccountHandleList.size(); i++) {
                        PhoneAccountHandle p = phoneAccountHandleList.get(i);
                        PhoneInfo info = new PhoneInfo();
                        info.simId = i;
                        info.simSerialNumber = p.getId();
                        list.add(info);
                    }
                }
            }
        }catch (Exception e){
            Log.d(TAG, "getSimInfo3 Exception");
            e.printStackTrace();
        }
        return list;
    }
}
